package com.yk.clienthandler;

import com.yk.business.CallBackMsg;
import com.yk.client.Loader;
import com.yk.pojo.ReqMessage;
import com.yk.pojo.RespMessage;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

/**
 * Created by dingkl on 2017/7/28.
 */
public class MessageSendHandler extends ChannelInboundHandlerAdapter{

    ConcurrentMap<String,CallBackMsg> msgConcurrentMap = new ConcurrentHashMap<>();

    ChannelHandlerContext channelHandlerContext;

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        channelHandlerContext = ctx;
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        System.out.println("channelRead");
        RespMessage respMessage = (RespMessage) msg;
        System.out.println("client:id-"+respMessage.getMessageId()+",code:"+respMessage.getCode()+",msg:"+respMessage.getMsg()+",data:"+respMessage.getData());
        CallBackMsg callBackMsg = msgConcurrentMap.get(respMessage.getMessageId());
        if (callBackMsg!=null){
            callBackMsg.over(respMessage);
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        /*cause.printStackTrace();
        ctx.close();
        Loader.loader().close();*/
        channelHandlerContext.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE);
    }

    public CallBackMsg sendMsg(ReqMessage reqMessage){
        CallBackMsg callBackMsg = new CallBackMsg();
        msgConcurrentMap.put(reqMessage.getMessageId(),callBackMsg);
        channelHandlerContext.writeAndFlush(reqMessage);
        System.out.println("send..");
        return callBackMsg;
    }
}
